const path = require("path");
const express = require("express");
const session = require("express-session");
const app = express();
const api = require("./router");
const connect = require("./connect");
const MongoStore = require("connect-mongo");
const defeneder = require("./middleware/defender");

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// D65ruogaLiA7bqia

// 配置session
app.use(
    session({
        name: "express",
        secret: "keyboard cat",
        resave: true, //【重新设置session后】会自动重新计算session的过期时间!
        saveUninitialized: true,
        cookie: {
            maxAge: 1000 * 60 * 60,
        },
        store: MongoStore.create({
            mongoUrl:
                "mongodb://newssession:HeX4PxphPJNF8GZB@47.120.64.39:27017/newssession",
            ttl: 1000 * 60 * 60,
        }),
    })
);

app.use("/api", api);
app.use("/static", express.static("static"));
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));

// 测试页面
app.get("/login", (req, res) => {
    if (req.session.user) return res.redirect("/");
    res.render("login");
});
app.get("/", defeneder, (req, res) => {
    res.render("index", { username: req.session.user.username });
});

app.listen(3000, () => {
    console.log("Server is running on port 3000");
});
